package com.my.bookstore.servlet;

import com.google.gson.Gson;
import com.my.bookstore.domain.Book;
import com.my.bookstore.domain.ShoppingCart;
import com.my.bookstore.service.BookService;
import com.my.bookstore.web.BookStoreWebUtils;
import com.my.bookstore.web.CriteriaBook;
import com.my.bookstore.web.Page;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by YJH on 2017/7/18 13:40.
 */
public class BookServlet extends HttpServlet {

    private BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String methodName = request.getParameter("method");
        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图书列表
     */
    private void getBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNoStr = request.getParameter("pageNo");
        String minPriceStr = request.getParameter("minPrice");
        String maxPriceStr = request.getParameter("maxPrice");

        int pageNo = 1;
        int minPrice = 0;
        int maxPrice = Integer.MAX_VALUE;

        try {
            pageNo = Integer.parseInt(pageNoStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        try {
            minPrice = Integer.parseInt(minPriceStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        try {
            maxPrice = Integer.parseInt(maxPriceStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        CriteriaBook criteriaBook = new CriteriaBook(minPrice, maxPrice, pageNo);

        Page<Book> page = bookService.getPage(criteriaBook);

        request.setAttribute("bookpage", page);

        request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response);
    }

    /**
     * 进入商品详情页面
     */
    private void getBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        int id = -1;
        Book book = null;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (id > 0) {
            book = bookService.getBook(id);
        }
        if (book == null) {
            response.sendRedirect(request.getContextPath() + "/error-1.jsp");
            return;
        }
        request.setAttribute("book", book);
        request.getRequestDispatcher("/WEB-INF/pages/book.jsp").forward(request, response);
    }

    /**
     * 添加商品到购物车
     */
    private void addToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取商品的id
        String idStr = request.getParameter("id");
        int id = -1;
        boolean flag = false;

        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (id > 0) {
            //2.获取购物车对象
            ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);

            //3.获取BookService的addToCart()方法把商品放到购物车中
            flag = bookService.addToCart(id, cart);
        }

        if (flag) {
            //4.直接调用getBooks()方法
            getBooks(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/error-1.jsp");
        }
    }

    /**
     * 跳转到购物车页面
     */
    private void toCartPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response);
    }

    /**
     * 从购物车中移除一件商品
     */
    private void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取商品的id
        String idStr = request.getParameter("id");
        int id = -1;

        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);
        bookService.removeItemFromShoppingCart(cart, id);

        if (cart.isEmpty()) {
            request.getRequestDispatcher("/WEB-INF/pages/emptyCart.jsp").forward(request, response); //转发
        }

        request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response); //转发
    }

    /**
     * 清空购物车
     */
    private void clearCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);
        bookService.clearShoppingCart(cart);

        request.getRequestDispatcher("/WEB-INF/pages/emptyCart.jsp").forward(request, response); //转发
    }

    /**
     * 修改图书的数量
     */
    private void updateItemQuantity(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //4.在updateItemQuantity方法中，获取quantity，id，在获取购物车对象，调用service的方法修改
        String idStr = request.getParameter("id");
        String quantityStr = request.getParameter("quantity");
        int id = -1;
        int quantity = -1;

        ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);

        try {
            id = Integer.parseInt(idStr);
            quantity = Integer.parseInt(quantityStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (id > 0 && quantity > 0) {
            bookService.updateItemQuantity(cart, id, quantity);
        }

        //5.传回JSON数据：bookNumber：xxx，totalMoney
        Map<String, Object> result = new HashMap<>();
        result.put("bookNumber", cart.getBookNumber());
        result.put("totalMoney", cart.getTotalMoney());

        Gson gson = new Gson();
        String jsonStr = gson.toJson(result);
        response.setContentType("text/javascript");
        response.getWriter().print(jsonStr);
    }
}
